import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import login from '@/views/login.vue'
import Welcome from '@/views/Welcome.vue'
import store from '@/store'
import UserInfo from '@/views/system/UserInfo.vue'

const routes = [
  { path: '/login', component: login, name: '登录' },

  {
    name: 'index',
    path: '/', component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome, name: '首页' },
      {
        path:'/userInfo',
        component:UserInfo,
        name:'基本信息'
      },
    ]
  },


  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/error')
  }

]

const router = createRouter({
  history: createWebHistory(),
  routes
})


router.beforeEach((to, from, next) => {

  let menuList = localStorage.getItem("menuList")
  menuList = JSON.parse(menuList)

  let token = localStorage.getItem("token")
  let hasRoute = store.state.menu.hasRoute
  console.log('hasroute',hasRoute)
  console.log('menulist',menuList)
  if (menuList && !hasRoute) {
    console.log('second--------------')
    bindRoute(menuList)
    store.commit("menu/SET_ROUTE_STATE", true)
    store.dispatch('chat/connect')

    next({ ...to, replace: true })
    // next()
  }
  else if(token || to.path == '/login'){
    next()
  }

  else{
    next('/login?redirect=' + to.path)
  }
})

const bindRoute = (menuList) => { 
  let newRoutes = router.options.routes
  console.log('menuList', menuList)

  menuList.forEach(parent => {
    if (parent.children) {

      parent.children.forEach(menu => {
        console.log('parent.foreach', menu)

        let route = menuToRoute(menu, parent.name)
        console.log('route',route)
        if (route) {

          router.addRoute('index', route)

        }
      })
      console.log('111111111111111111111111111')

    }
  })
  // router.addRoute(newRoutes)
}

// 导航转成路由
const menuToRoute = (menu, parentName) => {
  if (!menu.component) {
    return null
  }

  let str = menu.component

  menu.component = () => import('@/views/' + str + '.vue')
  return menu
}

export default router